import { action, makeAutoObservable } from 'mobx';
import moment, { Moment } from 'moment';
import global from '@/utils/global';

import {
  getUserMessage,
  deleteUserMessages,
  readUserMessage,
  readAllUserMessage,
  IGetUserMessageProps,
} from '@/services/messages';
import { isSameDevice } from '@/utils';

import deviceList from './deviceList';
import type { IDeviceMessageList } from '@/pages/notiCenter';

export interface IUserMessageItem {
  consumer: string; // 推送消费者
  content: string;
  msgContent: string;
  ctime: string | Moment;
  deleted: boolean;
  id: number;
  sceneId?: number;
  mac: string;
  msgType: number;
  noticeType: number;
  noticeId: number | null;
  handle: number;
  messageId: number;
  cname: string;
  noticeResultId: number;
  result: 1 | 2 | 3 | 4 | 5; //1发送成功 2发送失败 3未接听 4已接听 5通知失败
  name: string;
  pk: string;
  icon?: any;
  read: boolean;
  title: string;
  type: number;
  uid: string;
  userId: number;
  utime: string;
}

export interface IMessages {
  notiData: IUserMessageItem[];
  warnData: IUserMessageItem[];
  errorData: IUserMessageItem[];
}

const checkUnRead = (data: IUserMessageItem[]) => {
  let unRead = false;
  data.map(item => {
    if (item.read === false) {
      unRead = true;
    }
  });
  return unRead;
};

const updateTimeInterval = 4 * 1000;

class Messages implements IMessages {
  data: IUserMessageItem[] = [];
  notiData: IUserMessageItem[] = [];
  warnData: IUserMessageItem[] = [];
  errorData: IUserMessageItem[] = [];

  editDeviceMessages: IDeviceMessageList = {} as IDeviceMessageList;

  constructor() {
    makeAutoObservable(this);
    // this.timer = setInterval(() => {
    //   if (global && global.token) {
    //     this.getMessagesByNone();
    //   }
    // }, updateTimeInterval);
  }

  timer: any;

  get haveUnreadNotiMessage() {
    return checkUnRead(this.notiData);
  }
  get haveUnreadWarnMessage() {
    return checkUnRead(this.warnData);
  }
  get haveUnreadErrorMessage() {
    return checkUnRead(this.errorData);
  }

  get haveUnreadMessage() {
    return this.haveUnread(this.data);
  }

  @action
  haveUnread(messages: IUserMessageItem[]) {
    if (messages && messages.length > 0) {
      const index = messages.findIndex(i => {
        let unRead = false;
        if (i.read === false) {
          if (i.mac && deviceList.data.find(d => isSameDevice({ mac: i.mac, productKey: i.pk }, d))) {
            unRead = true;
          } else if (i.noticeType === 4) {
            // 这里过滤掉noticeType === 5的情况，这是智家的家庭分享，小程序不存在家庭
            if (i.handle === 1) {
              unRead = true;
            }
          }
        }
        return unRead;
      });
      return index > -1;
    }
    return false;
  }

  @action.bound
  setEditDeviceMessages(data: IDeviceMessageList) {
    this.editDeviceMessages = data;
  }

  @action.bound
  async setPartEditDeviceMessages({ productKey, mac }) {
    const res = await this.getDeviceMessages({ productKey, mac });
    if (res.success) {
      res.data?.map((i: IUserMessageItem) => (i.ctime = moment(i.ctime)));
      const content = res.data ?? [];
      this.editDeviceMessages = { ...this.editDeviceMessages, content };
    }
  }

  @action.bound
  async getMessagesByNone() {
    const data = await getUserMessage();
    if (data.success) {
      data.data?.map((i: IUserMessageItem) => (i.ctime = moment(i.ctime)));
      this.data = data.data ?? [];
    }
  }

  @action.bound
  async getDeviceMessages({ productKey, mac }: IGetUserMessageProps) {
    console.log('productKey, mac', productKey, mac);
    return getUserMessage({ productKey, mac });
  }

  @action.bound
  async readDeviceMessages({ productKey, mac }: IGetUserMessageProps) {
    console.log('productKey, mac', productKey, mac);
    return readAllUserMessage({ productKey, mac });
  }

  // @action.bound
  // async getMessages(msgType: TMessageTyps, read?: boolean = false) {
  //   // this.notiData = this.formatData(testData);
  //   const data = await getUserMessage({ msgType });
  //   if (data.success) {
  //     // eslint-disable-next-line no-param-reassign
  //     (data.data as IUserMessageItem[]).map((i: IUserMessageItem) => (i.ctime = moment(i.ctime)));
  //     switch (msgType) {
  //       case '1': {
  //         this.warnData = data.data as IUserMessageItem[];
  //         break;
  //       }
  //       case '2': {
  //         this.errorData = data.data as IUserMessageItem[];
  //         break;
  //       }
  //       case '3': {
  //         this.notiData = data.data as IUserMessageItem[];
  //         break;
  //       }
  //     }
  //     if (read) {
  //       (data.data as IUserMessageItem[]).map(item => {
  //         if (item.read === false) {
  //           this.readUserMessage(item);
  //         }
  //       });
  //     }
  //   }
  // }

  @action.bound
  async deleteUserMessages(arr: number[]) {
    return deleteUserMessages(arr);
  }

  @action.bound
  async readUserMessage(item: IUserMessageItem) {
    return readUserMessage(item.id);
  }
}

const Message_Store_Key = 'messages';
export { Messages, Message_Store_Key };
export default new Messages();
